package com.yami.shop.personnft.api.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.ChannelUserRelationRecord;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.ChannelUserRelationRecordService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.SysConfigService;
import com.yami.shop.service.UserService;
import com.yami.shop.user.common.model.UserGasInfo;
import com.yami.shop.user.common.service.UserGasInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * spu信息
 *
 * @author FrozenWatermelon
 * @date 2020-10-28 15:27:24
 */
@RestController("userDtcController")
@RequestMapping("/dtc/app/user")
@Tag(name = "userDtc信息")
@AllArgsConstructor
@Slf4j
public class UserDtcController {
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ChannelUserRelationRecordService channelUserRelationRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserGasInfoService userGasInfoService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ShopConfig shopConfig;
    /**
     * @return
     */
    @GetMapping("/getHomeList")
    @Operation(summary = "用户渠道列表", description = "用户")
    public ServerResponseEntity getHomeList() {
        // 查询渠道信息
        String userId = SecurityUtils.getUser().getUserId();
        List<Map<String, Object>> homeChannelList = channelUserRelationRecordService.getHomeChannelList(userId);
        // 返回用户渠道对象
        return ServerResponseEntity.success(homeChannelList);
    }

    /**
     * @return
     */
    @GetMapping("/isExportUserByUserId")
    @Operation(summary = "用户渠道列表", description = "用户")
    public ServerResponseEntity isExportUserByUserId() {
        // 查询渠道信息
        String userId = SecurityUtils.getUser().getUserId();
        List<Map<String, Object>> homeChannelList = channelUserRelationRecordService.getHomeChannelList(userId);
        // 查询gas
        Integer gas = 0;
        UserGasInfo one = userGasInfoService.getOne(new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, userId));
        if (one != null) {
            gas = one.getGasNumber();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("allHomeAllChanne", homeChannelList);
        map.put("gas", gas);
        String url = sysConfigService.getValue("gasUrl");
        map.put("gasUrl", url);
        // 返回用户渠道对象
        return ServerResponseEntity.success(map);
    }

    @GetMapping("/isExportChannelChainInfoByUserIdAndChannel")
    @Operation(summary = "渠道对应的链", description = "用户")
    public ServerResponseEntity isExportChannelChainInfoByUserIdAndChannel(String channelCode) {
        String userId = SecurityUtils.getUser().getUserId();
        List<Map<String, Object>> homeChannelList = channelUserRelationRecordService.getHomeChainList(userId, channelCode);
        // 返回用户渠道对象
        return ServerResponseEntity.success(homeChannelList);
    }


    @GetMapping("/getCreateUserChainChannelList")
    @Operation(summary = "新添加的链渠道总和列表", description = "用户")
    public ServerResponseEntity getCreateUserChainChannelList() {
        String userId = SecurityUtils.getUser().getUserId();
        List<Map<String, Object>> newUserChannel = channelUserRelationRecordService.getCreateUserChainChannelList(userId);
        return ServerResponseEntity.success(newUserChannel);
    }

    /**
     * 地址簿
     *
     * @return
     */
    @GetMapping("/allChannelList")
    @Operation(summary = "获取平台列表（不分页）", description = "获取链平台列表（不分页）")
    public ServerResponseEntity allChannelList(String chainCode) {
        List<Map<String, Object>> blockchains = channelUserRelationRecordService.allChannelList(chainCode);
        return ServerResponseEntity.success(blockchains);
    }

    /**
     * 地址簿和已创建
     *
     * @return
     */
    @GetMapping("/userChainList")
    @Operation(summary = "获取用户链平台列表（不分页）", description = "获取链平台列表（不分页）")
    public ServerResponseEntity userChainList() {
        String userId = SecurityUtils.getUser().getUserId();
        List<Map<String, Object>> blockchains = channelUserRelationRecordService.userBlockchain(userId);
        return ServerResponseEntity.success(blockchains);
    }

    @GetMapping("/getUserHasChannelList")
    @Operation(summary = "已创建渠道列表", description = "用户")
    public ServerResponseEntity getUserHasChannelList(String chainCode) {
        String userId = SecurityUtils.getUser().getUserId();
        List<Map<String, Object>> newUserChannel = channelUserRelationRecordService.getUserHasChannelList(userId, chainCode);
        // 返回用户渠道对象
        return ServerResponseEntity.success(newUserChannel);
    }

    @GetMapping("/createUserChannel")
    @Operation(summary = "新创建渠道", description = "用户")
    public ServerResponseEntity createUserChannel(String channelCode, String chainCode) {
        String userId = SecurityUtils.getUser().getUserId();
        if (StrUtil.isEmpty(channelCode) || StrUtil.isEmpty(chainCode) || StrUtil.isNullOrUndefined(channelCode) || StrUtil.isNullOrUndefined(chainCode)) {
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.sys.illegalArgument"));
        }
        if(RedisUtil.hasKey("createDtcAddress"+userId)){
            throw new YamiShopBindException("yami.channel.request");
        }
        RedisUtil.set("createDtcAddress"+userId,"true",60);
        try {
            User userByUserId = userService.getUserByUserId(userId);
            if(StrUtil.isBlank(userByUserId.getIdNumber())){
                throw new YamiShopBindException("yami.dtc.check.realname");
            }
            ShopDetail shopDetailByShopCode = shopDetailService.getShopDetailByShopCode(channelCode);
            if("1".equals(shopDetailByShopCode.getAgeCheck())){
                Boolean bigMan = userService.isBigMan(userByUserId.getIdNumber());
                if(!bigMan){
                    throw new YamiShopBindException("yami.dtc.channel.check.age");
                }
            }
            channelUserRelationRecordService.createUserChannel(userId, chainCode, channelCode);
        // 返回用户渠道对象
            return ServerResponseEntity.success();
        }catch (Exception e){
            log.error("创建钱包异常",e);
            throw new YamiShopBindException(e.getMessage());
        }finally {
            RedisUtil.del("createDtcAddress"+userId);
        }
    }


    @GetMapping("/isHasDTCAddress")
    @Operation(summary = "微发行是否有地址", description = "用户")
    public ServerResponseEntity isHasDTCAddress(String channelCode, String chainCode) {
        String userId = SecurityUtils.getUser().getUserId();
        return ServerResponseEntity.success(channelUserRelationRecordService.isHasDTCAddress(userId, chainCode, channelCode));
    }

    @GetMapping("/removeAddress")
    @Operation(summary = "解绑", description = "用户")
    public ServerResponseEntity removeAddress(String channelCode, String chainCode) {
        String userId = SecurityUtils.getUser().getUserId();
        channelUserRelationRecordService.removeAddress(userId, chainCode, channelCode);
        return ServerResponseEntity.success();
    }

    @GetMapping("/isHasAllAddress")
    @Operation(summary = "用户是否有地址", description = "用户")
    public ServerResponseEntity isHasAllAddress(String channelCode, String chainCode, String type) {
        String userId = SecurityUtils.getUser().getUserId();
        return ServerResponseEntity.success(channelUserRelationRecordService.isHasAllAddress(userId, chainCode, channelCode, type));
    }

    /**
     * 下单，微发行实名，红包
     *
     * @param channelCode
     * @param chainCode
     * @return
     */
    @GetMapping("/createDtcAddress")
    @Operation(summary = "创建微发行地址", description = "用户")
    public ServerResponseEntity createDtcAddress(String channelCode, String chainCode) {
        String userId = SecurityUtils.getUser().getUserId();
        if (StrUtil.isEmpty(channelCode) || StrUtil.isEmpty(chainCode) || StrUtil.isNullOrUndefined(channelCode) || StrUtil.isNullOrUndefined(chainCode)) {
            return ServerResponseEntity.showFailMsg("参数异常");
        }
        if(RedisUtil.hasKey("createDtcAddress"+userId)){
            throw new YamiShopBindException("yami.channel.request");
        }
        RedisUtil.set("createDtcAddress"+userId,"true",60);
        try {
            User userByUserId = userService.getUserByUserId(userId);
            if(StrUtil.isBlank(userByUserId.getIdNumber())){
                throw new YamiShopBindException("yami.dtc.check.realname");
            }
            ShopDetail shopDetailByShopCode = shopDetailService.getShopDetailByShopCode(channelCode);
            if("1".equals(shopDetailByShopCode.getAgeCheck())){
                Boolean bigMan = userService.isBigMan(userByUserId.getIdNumber());
                if(!bigMan){
                    throw new YamiShopBindException("yami.dtc.channel.check.age");
                }
            }
            channelUserRelationRecordService.createDtcAddress(userId, chainCode, channelCode);
            return ServerResponseEntity.success();
        }catch (Exception e){
            throw new YamiShopBindException(e.getMessage());
        }finally {
            RedisUtil.del("createDtcAddress"+userId);
        }
    }
    @GetMapping("/checkAddressAndCreateAddress")
    @Operation(summary = "产权登记总和判断是否有地址和创建地址", description = "用户")
    public ServerResponseEntity getUserAllAddress(String channelCode, String chainCode) {
        String userId = SecurityUtils.getUser().getUserId();
        if(StrUtil.isEmpty(channelCode)){
            channelCode = shopConfig.getWorksConfig().getChannelCode();
            chainCode = shopConfig.getWorksConfig().getChainCode();
        }
        Boolean hasDTCAddress = channelUserRelationRecordService.isHasDTCAddress(userId, chainCode, channelCode);
        if(!hasDTCAddress){
            if(RedisUtil.hasKey("createDtcAddress"+userId)){
                throw new YamiShopBindException("yami.channel.request");
            }
            RedisUtil.set("createDtcAddress"+userId,"true",60);
            try {
                User userByUserId = userService.getUserByUserId(userId);
                if(StrUtil.isBlank(userByUserId.getIdNumber())){
                    throw new YamiShopBindException("yami.dtc.check.realname");
                }
                ShopDetail shopDetailByShopCode = shopDetailService.getShopDetailByShopCode(channelCode);
                if("1".equals(shopDetailByShopCode.getAgeCheck())){
                    Boolean bigMan = userService.isBigMan(userByUserId.getIdNumber());
                    if(!bigMan){
                        throw new YamiShopBindException("yami.dtc.channel.check.age");
                    }
                }
                channelUserRelationRecordService.createDtcAddress(userId, chainCode, channelCode);
            }catch (Exception e){
                throw new YamiShopBindException(e.getMessage());
            }finally {
                RedisUtil.del("createDtcAddress"+userId);
            }
        }
        return ServerResponseEntity.success();
    }

    /**
     * 获取用户木渠道链下的多地址列表
     *
     * @param channelCode
     * @param chainCode
     * @return
     */
    @GetMapping("/getUserAllAddress")
    @Operation(summary = "用户多地址列表", description = "用户")
    public ServerResponseEntity getUserAllAddress(String channelCode, String chainCode,Long isRed) {
        String userId = SecurityUtils.getUser().getUserId();
        List<ChannelUserRelationRecord> userAllAddress = channelUserRelationRecordService.getUserAllAddress(userId, chainCode, channelCode,isRed);
        return ServerResponseEntity.success(userAllAddress);
    }

    /**
     * 选择多链任意一个
     *
     * @return
     */
    @GetMapping("/getUserOneAddress")
    @Operation(summary = "用户多地址列表", description = "用户")
    public ServerResponseEntity getUserOneAddress(String type) {
        String userId = SecurityUtils.getUser().getUserId();
        Map<String, Object> userOneAddress = channelUserRelationRecordService.getUserOneAddress(userId, type);
        return ServerResponseEntity.success(userOneAddress);
    }

    /**
     * 获取用户随机链展示
     *
     * @return
     */
    @GetMapping("/getChannelInfo")
    @Operation(summary = "获取用户随机链展示", description = "用户")
    public ServerResponseEntity<Map<String, Object>> getChannelInfo(String channelCode, String chainCode) {
        // 查询用户信息
        String userId = SecurityUtils.getUser().getUserId();
        Map<String, Object> map = channelUserRelationRecordService.getChannelInfo(userId, chainCode, channelCode, null);
        return ServerResponseEntity.success(map);
    }

    @GetMapping("/getChannelInfoByType")
    @Operation(summary = "获取用户随机链展示", description = "用户")
    public ServerResponseEntity<Map<String, Object>> getChannelInfoByType(String channelCode, String chainCode, String type) {
        // 查询用户信息
        String userId = SecurityUtils.getUser().getUserId();
        Map<String, Object> map = channelUserRelationRecordService.getChannelInfo(userId, chainCode, channelCode, type);
        return ServerResponseEntity.success(map);
    }

    /**
     * 获取持仓页面调用次数 ，是否弹引导弹框
     *
     * @return
     */
    @GetMapping("/getPositionGuidance")
    @Operation(summary = "引导提示", description = "分页获取平台信息列表")
    public ServerResponseEntity<Boolean> getPositionGuidance() {
        // 持仓引导
        String userId = SecurityUtils.getUser().getUserId();
        if (RedisUtil.hasKey("POSITIONGUIDANCEEXPORT::" + userId)) {
            RedisUtil.del("POSITIONGUIDANCEEXPORT::" + userId);
            return ServerResponseEntity.success(true);
        } else {
            return ServerResponseEntity.success(false);
        }
    }


    /**
     * 创建钱包=静默注册+实名
     */
    @GetMapping("/registerAndAuthentication")
    @Operation(summary = "创建钱包", description = "个人持仓")
    public ServerResponseEntity registerAndAuthentication(String channelCode, String chainCode) {
        // 检查权限
        if (StringUtils.isEmpty(channelCode)) {
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        String userId = SecurityUtils.getUser().getUserId();
        ChannelUserRelationRecord record = channelUserRelationRecordService.exportChannelAddress(userId, chainCode, channelCode);
        // 返回用户渠道对象
        return ServerResponseEntity.success(record);
    }

    @GetMapping("/getUserByCallPhone")
    @Operation(summary = "获取用户通过电话", description = "个人持仓")
    public ServerResponseEntity getUserByCallPhone(String callPhone) {
        String userId = SecurityUtils.getUser().getUserId();
        if (StringUtils.isEmpty(callPhone)) {
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        try {
            Map<String, Object> userByCallPhone = channelUserRelationRecordService.getUserByCallPhone(userId, callPhone);
            return ServerResponseEntity.success(userByCallPhone);
        } catch (MailException e) {
            return ServerResponseEntity.showFailMsg(e.getMessage());
        } catch (YamiShopBindException e) {
            return ServerResponseEntity.showFailMsg("查询失败");
        }
    }
    @GetMapping("/isBigMan")
    @Operation(summary = "是否成年人", description = "个人持仓")
    public ServerResponseEntity isBigMan() {
        String userId = SecurityUtils.getUser().getUserId();
        User userByUserId = userService.getUserByUserId(userId);
        if(StrUtil.isBlank(userByUserId.getIdNumber())){
            return ServerResponseEntity.success(true);
        }
        Boolean bigMan = userService.isBigMan(userByUserId.getIdNumber());
        return ServerResponseEntity.success(bigMan);
    }


}
